local w = require('utils.win')
local m = require('utils.vim')
local b = require('utils.buf')
local e = require('utils.editor')

local git_commit = function(cmd)
    if w.is_floating() then
        w.close_current_floating_window()
    end

    -- Create a new floating window for the terminal
    local width = math.floor(vim.o.columns * 0.8)  -- 80% of the screen width
    local height = math.floor(vim.o.lines * 0.8)   -- 80% of the screen height
    local row = math.floor((vim.o.lines - height) / 2)  -- Center vertically
    local col = math.floor((vim.o.columns - width) / 2) -- Center horizontally

    -- Create the floating window
    local buf = vim.api.nvim_create_buf(false, true) -- Create a new buffer
    local win = vim.api.nvim_open_win(buf, true, {
        relative = 'editor',
        width = width,
        height = height,
        col = col,
        row = row,
        border = 'single',
        style = 'minimal',
    })

    -- Open terminal in the new popup window
    vim.fn.termopen(cmd)

    -- Set buffer options
    vim.bo[buf].bufhidden = 'delete'
    vim.wo[win].number = false
    vim.wo[win].relativenumber = false

    -- Start insert mode
    vim.cmd('startinsert')

    -- Save the current buffer number to restore syntax later
    local current_bufnr = vim.fn.bufnr('%')

    -- Set up an autocommand to close the floating window when the process exits
    vim.cmd([[
        augroup git_commit_term
        autocmd!
        autocmd TermClose <buffer> call v:lua.on_term_close(bufnr('%'))
        augroup END
        ]])
end

-- Function to handle terminal closing
function _G.on_term_close(bufnr)
    local status = vim.v.event.status or 0  -- Default to 0 if 'status' does not exist

    if status == 0 then
        -- If the terminal process exited normally
        if bufnr and vim.api.nvim_buf_is_valid(bufnr) then
            vim.api.nvim_buf_delete(bufnr, {force = true})
        end

        --avoid syntax off of current buffer
        w.create_mock_floating_window()
        vim.defer_fn(function()
            e.send_key("q")
        end, 100)
    end
end

m.map("n", "<space>g", function()
    local cmd = 'source ~/fish && c && gs'
    git_commit(cmd)
end,{desc="git commit for current project"})
m.map("n", "<space>h", function()
    local cmd = 'source ~/fish && c && gs && cd /mnt/c/Users/FANGZX/wxapp && git pull'
    git_commit(cmd)
end,{desc="git commit for current project used by wxapp development"})

-- EOP
